<template>
  <div class="monitor-dashboard">
    <!-- 统计卡片区 -->
    <div class="alert-cards">
      <template v-if="!isLoading">
        <AlertCard
          v-for="card in alertCards"
          :key="card.key"
          :title="card.title"
          :count="card.count"
          :diff="card.diff"
          :color="card.color"
        />
      </template>
      <template v-else>
        <div v-for="i in 4" :key="i" class="alert-card-skeleton"></div>
      </template>
    </div>

    <!-- 告警表格 -->
    <a-card class="alert-table-card">
      <div class="table-header">
        <span class="table-title">告警列表</span>
        <div class="table-actions">
          <a-button type="primary" @click="refresh" size="small" class="action-button">刷新数据</a-button>
          <a-button @click="clearCompleted" danger size="small">清除已完成</a-button>
        </div>
      </div>
      <div class="table-scroll-area">
        <a-table
          :loading="isLoading"
          :columns="columns"
          :data-source="tableData"
          :pagination="false"
          row-key="id"
          :scroll="{ x: '800px', y: '350px' }"
          size="small"
          class="alert-table"
        />
      </div>
    </a-card>

    <!-- 下方分析区 -->
    <div class="analysis-section">
      <a-card class="trend-card">
        <div class="section-title">告警趋势分析</div>
        <div v-if="trendLoading" class="chart-loading-indicator">
          <a-spin size="small" />
        </div>
        <div ref="trendChartRef" class="chart-box"></div>
      </a-card>
      <a-card class="pie-card">
        <div class="section-title">告警类型分布</div>
        <div v-if="pieLoading" class="chart-loading-indicator">
          <a-spin size="small" />
        </div>
        <div ref="pieChartRef" class="chart-box"></div>
      </a-card>
    </div>
    
    <!-- 页面级消息提示 -->
    <div class="monitor-messages" v-if="monitorMessages.length">
      <transition-group name="message-fade">
        <div v-for="msg in monitorMessages" :key="msg.id" :class="['monitor-message', `monitor-message-${msg.type}`]">
          <span class="message-content">{{ msg.content }}</span>
        </div>
      </transition-group>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, h, nextTick, onUnmounted } from 'vue'
import AlertCard from '@/components/AlertCard/index.vue'
import { getAlertSummary, getAlertList, getAlertTrend, getAlertTypePie } from '@/api/alert'
import * as echarts from 'echarts'
import { Tag } from 'ant-design-vue'

const alertCards = ref([])
const tableData = ref([])
let trendChart = null
let pieChart = null
const isLoading = ref(true)
const trendLoading = ref(true)
const pieLoading = ref(true)

// 页面级消息管理
const monitorMessages = ref([])
let messageIdCounter = 0

// 页面级消息系统
const showPageMessage = (content, type = 'info', duration = 3000) => {
  const id = messageIdCounter++
  const msg = { id, content, type }
  monitorMessages.value.push(msg)
  
  // 自动移除消息
  setTimeout(() => {
    const index = monitorMessages.value.findIndex(m => m.id === id)
    if (index !== -1) {
      monitorMessages.value.splice(index, 1)
    }
  }, duration)
  
  return id
}

function handleLog(record) {
  showPageMessage(`开始处理告警: ${record.content}`, 'info')
  record.status = '处理中'
}

const levelColorMap = {
  '危急': 'red',
  '重要': 'orange',
  '次要': 'blue'
}

const columns = [
  { title: '告警时间', dataIndex: 'time', key: 'time', ellipsis: true },
  {
    title: '告警级别',
    dataIndex: 'level',
    key: 'level',
    width: 90,
    customRender: ({ text }) => {
      return h(
        Tag,
        { color: levelColorMap[text] || 'default', style: 'font-weight:bold;' },
        { default: () => text }
      )
    }
  },
  { title: '告警类型', dataIndex: 'type', key: 'type', width: 120, ellipsis: true },
  { title: '告警对象', dataIndex: 'target', key: 'target', width: 160, ellipsis: true },
  { title: '告警内容', dataIndex: 'content', key: 'content', ellipsis: true },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    fixed: 'right',
    customRender: ({ text, record }) => {
      if (text === '未处理') {
        return h(
          'button',
          {
            class: 'handle-btn',
            onClick: () => handleLog(record)
          },
          '处理'
        )
      }
      return text
    }
  }
]

const trendChartRef = ref(null)
const pieChartRef = ref(null)

// 处理图表响应式
function handleResize() {
  if (trendChart) trendChart.resize()
  if (pieChart) pieChart.resize()
}

// 创建趋势图骨架
function createTrendSkeleton() {
  if (!trendChartRef.value) return
  
  const chart = echarts.init(trendChartRef.value)
  chart.setOption({
    title: {
      text: '加载中...',
      left: 'center',
      textStyle: { fontSize: 14, color: '#999' }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['', '', '', '', '', '', ''],
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: { show: false }
    },
    yAxis: {
      type: 'value',
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: { show: false },
      splitLine: { show: true, lineStyle: { color: '#f5f5f5' } }
    },
    series: [{
      type: 'line',
      data: [0, 0, 0, 0, 0, 0, 0],
      lineStyle: { color: '#f0f0f0' },
      itemStyle: { color: '#f0f0f0' },
      areaStyle: { color: '#fafafa' },
      smooth: true
    }]
  })
  return chart
}

// 创建饼图骨架
function createPieSkeleton() {
  if (!pieChartRef.value) return
  
  const chart = echarts.init(pieChartRef.value)
  chart.setOption({
    title: {
      text: '加载中...',
      left: 'center',
      textStyle: { fontSize: 14, color: '#999' }
    },
    series: [{
      type: 'pie',
      radius: ['40%', '65%'],
      center: ['50%', '38%'],
      data: [
        { value: 1, name: '', itemStyle: { color: '#f5f5f5' } }
      ],
      label: { show: false },
      labelLine: { show: false },
      animation: false
    }]
  })
  return chart
}

// 单独加载趋势图数据
async function loadTrendChart() {
  try {
    const trendData = await getAlertTrend()
    if (trendChartRef.value) {
      if (!trendChart) {
        trendChart = echarts.init(trendChartRef.value)
      }
      trendChart.setOption({
        tooltip: { trigger: 'axis' },
        legend: { data: trendData.legend, type: 'scroll', bottom: 10 },
        grid: { left: '3%', right: '4%', bottom: '18%', top: '5%', containLabel: true },
        xAxis: { type: 'category', data: trendData.xAxis, axisLabel: { interval: 0, rotate: 30 } },
        yAxis: { type: 'value' },
        series: trendData.series.map(item => ({
          name: item.name,
          type: 'line',
          data: item.data,
          smooth: true
        }))
      }, true)
    }
    trendLoading.value = false
  } catch (error) {
    console.error('加载趋势图失败:', error)
    trendLoading.value = false
  }
}

// 单独加载饼图数据
async function loadPieChart() {
  try {
    const pieData = await getAlertTypePie()
    if (pieChartRef.value) {
      if (!pieChart) {
        pieChart = echarts.init(pieChartRef.value)
      }
      pieChart.setOption({
        tooltip: { trigger: 'item' },
        legend: { 
          orient: 'horizontal', 
          bottom: 10, 
          left: 'center', 
          data: pieData.legend,
          type: 'scroll',
          padding: [5, 10, 15, 10]
        },
        series: [
          {
            name: '告警类型',
            type: 'pie',
            radius: ['40%', '65%'],
            center: ['50%', '38%'],
            avoidLabelOverlap: false,
            label: { show: false, position: 'center' },
            emphasis: { label: { show: true, fontSize: 14, fontWeight: 'bold' } },
            labelLine: { show: false },
            data: pieData.series
          }
        ]
      }, true)
    }
    pieLoading.value = false
  } catch (error) {
    console.error('加载饼图失败:', error)
    pieLoading.value = false
  }
}

// 加载表格和卡片数据
async function loadTableData() {
  try {
    // 并行请求数据
    const [cards, listRes] = await Promise.all([
      getAlertSummary(),
      getAlertList({ page: 1, pageSize: 1000 })
    ])
    
    alertCards.value = cards
    tableData.value = listRes.list
    isLoading.value = false
  } catch (error) {
    console.error('加载表格数据失败:', error)
    isLoading.value = false
  }
}

async function fetchData() {
  isLoading.value = true
  trendLoading.value = true
  pieLoading.value = true
  
  // 创建骨架图
  trendChart = createTrendSkeleton()
  pieChart = createPieSkeleton()
  
  // 并行加载所有数据
  await Promise.all([
    loadTableData(),
    loadTrendChart(),
    loadPieChart()
  ])
}

function refresh() {
  fetchData()
}

function clearCompleted() {
  tableData.value = tableData.value.filter(item => item.status === '未处理')
}

onMounted(() => {
  // 立即创建骨架图
  nextTick(() => {
    trendChart = createTrendSkeleton()
    pieChart = createPieSkeleton()
    
    // 开始加载实际数据
    fetchData()
  })
  
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (trendChart) trendChart.dispose()
  if (pieChart) pieChart.dispose()
})
</script>

<style scoped>
.monitor-dashboard {
  height: 100%;
  box-sizing: border-box;
  padding: 16px;
  padding-bottom: 24px; /* 增加底部间距 */
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.alert-cards {
  display: flex;
  gap: 16px;
  margin-bottom: 0;
  flex-wrap: wrap;
}

.alert-card-skeleton {
  flex: 1 1 200px;
  min-height: 90px;
  background: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 50%, #f2f2f2 75%);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
  border-radius: 10px;
}

@keyframes loading {
  0% { background-position: 200% 0 }
  100% { background-position: -200% 0 }
}

.chart-loading-indicator {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 10;
}

.alert-table-card {
  flex: 1 1 auto;
  display: flex;
  flex-direction: column;
  min-height: 200px;
  overflow: visible;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  flex-wrap: wrap;
  gap: 8px;
}

.table-title {
  font-weight: 500;
  font-size: 16px;
}

.table-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-button {
  margin-right: 0;
}

.table-scroll-area {
  flex: 1 1 auto;
  position: relative;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  height: 400px;
  overflow: hidden;
}

:deep(.alert-table) {
  height: 100%;
}

:deep(.ant-table-wrapper),
:deep(.ant-spin-nested-loading),
:deep(.ant-spin-container) {
  height: 100%;
}

:deep(.ant-table) {
  height: 100%;
}

:deep(.ant-table-container) {
  height: 100%;
}

:deep(.ant-table-body) {
  height: calc(100% - 39px) !important;
  overflow-y: auto !important;
  overflow-x: auto !important;
}

:deep(.ant-table-thead > tr > th) {
  position: sticky;
  top: 0;
  z-index: 2;
  background: #fafafa;
}

:deep(.ant-table-tbody > tr:last-child > td) {
  padding-bottom: 8px;
}

.analysis-section {
  display: flex;
  gap: 16px;
  flex: 1 1 auto;
  min-height: 280px;
  flex-wrap: wrap;
  margin-bottom: 24px; /* 增加底部间距 */
  padding-bottom: 16px; /* 内部底部填充 */
}

.trend-card, .pie-card {
  flex: 1 1 400px;
  display: flex;
  flex-direction: column;
  min-width: 0;
  min-height: 280px;
  position: relative;
}

.chart-box {
  width: 100%;
  height: 100%;
  min-height: 240px;
  flex: 1;
  padding-bottom: 20px; /* 确保图表下方有足够空间 */
}

.section-title {
  font-weight: bold;
  margin-bottom: 8px;
}

.handle-btn {
  background: #1677ff;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 2px 8px;
  cursor: pointer;
  font-size: 13px;
}

.handle-btn:hover {
  background: #409eff;
}

/* 响应式样式 */
@media (max-width: 1200px) {
  .analysis-section {
    flex-direction: column;
    margin-bottom: 32px; /* 增加底部间距 */
  }
  
  .trend-card, .pie-card {
    flex: 1 1 280px;
    margin-bottom: 16px; /* 卡片间距 */
  }
}

@media (max-width: 768px) {
  .alert-cards {
    flex-direction: column;
  }
  
  .alert-cards > * {
    width: 100%;
  }
  
  .chart-box {
    min-height: 200px;
  }
}

/* 保证表格内容不溢出 */
:deep(.ant-table-cell) {
  white-space: nowrap;
}

:deep(.ant-card-body) {
  padding: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: visible; /* 允许内容溢出 */
}

/* 页面级消息样式 */
.monitor-messages {
  position: fixed;
  top: 16px;
  right: 16px;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.monitor-message {
  padding: 8px 16px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  animation: slide-in 0.3s ease;
  min-width: 200px;
}

.monitor-message-info {
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
}

.monitor-message-success {
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
}

.monitor-message-warning {
  background-color: #fffbe6;
  border: 1px solid #ffe58f;
}

.monitor-message-error {
  background-color: #fff2f0;
  border: 1px solid #ffccc7;
}

.message-fade-enter-active,
.message-fade-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}

.message-fade-enter-from,
.message-fade-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

@keyframes slide-in {
  from {
    transform: translateX(30px);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}
</style> 